<template>
  <div class="signature-main" id="signature-main" onselectstart="return false">
    <div class="left" id="signature-canvas-parent" ref="signatureCanvasParent">
      <!-- <signature-canvas
        ref="signaturePad"
        :url="imageUrl"
        :width="signatureCanvasWidth" :height="signatureCanvasHeight"
        :images="fileList"
      ></signature-canvas> -->
      <drawing-board :image="imageUrl"></drawing-board>
    </div>
    <div class="right" v-contextmenu="handleContextmenu" :style="`right: 10px;top: 0px`" ref="right">
      <!-- list-type="picture" -->
      <!-- :file-list="fileList" -->
      <el-upload
        :multiple="false"
        class="upload-demo"
        ref="upload"
        action="https://jsonplaceholder.typicode.com/posts/"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-change="handleChange"
        :showFileList="false"
        list-type="picture"
        :file-list="fileList"
        :auto-upload="false">
        <el-button slot="trigger" size="mini" type="primary">选取文件</el-button>
        <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
      </el-upload>
      <!-- <div class="foot">
        <el-button type="success" size="mini" @click="save">保存文件</el-button>
        <el-button type="warning" size="mini" @click="undo">撤销</el-button>
        <el-button type="warning" size="mini" @click="clearSignature">清空</el-button>
      </div> -->

    </div>
  </div>
</template>
<script>

/*#region 导入函数*/
import SignatureCanvas from "./signature-canvas/signature-canvas";
import VueSignaturePad from "./vue-signature-pad/VueSignaturePad.js";
import FileSaver from "file-saver";
import Hammer from "hammerjs";
import DrawingBoard from "./drawingboard/drawing-board";
import White from "./drawingboard/white.jpg";

/*#endregion*/

export default{
  name: "SignaturePic",
  methods: {

    /*#region 自定义函数(组件change事件等)*/
    undo() {
      this.$refs.signaturePad.undoSignature();
    },
    clearCacheImages() {
      this.$refs.signaturePad.clearCacheImages();
    },
    clearSignature() {
      this.$refs.signaturePad.clearSignature();
    },
    save() {
      const { isEmpty, data } = this.$refs.signaturePad.saveSignature();
      this.image = data;
      if (!isEmpty) {
        const fileName = this.fileList.length > 0 ? this.fileList[0].name : "下载.png";
        // const blob = new Blob([data], {type: "text/plain;charset=utf-8"});
        const download = (data, fileName, type) => {
          const fixtype = function(type) {
            type = type.toLowerCase().replace(/jpg/i, 'jpeg');
            const r = type.match(/png|jpeg|bmp|gif/)[0];
            return 'image' + r;
          };
          data = data.replace(fixtype(type), 'image/octet-stream');
          const saveFile = function (data, filename) {
            const link = document.createElement('a');
            link.href = data;
            link.download = filename;
            link.click();
          };
          const filename = new Date().toLocaleDateString() + '.' + type;
          saveFile(data, filename);
        };
        // FileSaver.saveAs(data, fileName);
        download(data, fileName, "png");
      }
    },

    /*#endregion*/

    /*#region 数据提交事件*/

    /*#endregion*/

    /*#region 操作函数(handle)*/
    submitUpload() {
      // this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
    },
    handlePreview(file) {
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1);
      if (this.fileList.length > 0) {
        const image = new Image();
        image.src = this.fileList[0].url;
        image.onload = () => {
          if (image.height > window.document.body.clientHeight) {
            this.signatureCanvasHeight = window.document.body.clientHeight;
          } else {
            this.signatureCanvasHeight = image.height;
          }
          if (image.width > window.document.body.clientWidth) {
            this.signatureCanvasWidth = window.document.body.clientWidth - 10;
          } else {
            this.signatureCanvasWidth = image.width;
          }
        };
      }

      console.log(file, fileList, "handleChange");
    },
    handleContextmenu(event, type) {
      this.right.x = event.clientX;
      this.right.y = event.clientY;
    }

    /*#endregion*/

    /*#region 获取数据*/

     /*#endregion*/

  },

  /*#region 生命周期函数(created、mount、等)*/
  created() {
      this.right.x = window.innerWidth;
  },
  mounted() {
    if (this.imageUrl) {
      const image = new Image();
      image.src = this.imageUrl;
      image.onload = () => {
        if (image.height > window.document.body.clientHeight) {
          this.signatureCanvasHeight = window.document.body.clientHeight;
        } else {
          this.signatureCanvasHeight = image.height;
        }
        if (image.width > window.document.body.clientWidth) {
          this.signatureCanvasWidth = window.document.body.clientWidth;
        } else {
          this.signatureCanvasWidth = image.width;
        }
      };
    } else {
      this.signatureCanvasHeight = window.document.body.clientHeight ? window.document.body.clientHeight - 10 : "100%";
      this.signatureCanvasWidth = window.document.body.clientWidth ? window.document.body.clientWidth - 10 : "100%";
    }
    // if(this.$refs.signatureCanvasParent){
    //   this.hammerTest = new Hammer(this.$refs.signatureCanvasParent);
    //   this.hammerTest.get('pinch').set({ enable: true });
    //   this.hammerTest.on("pinch", function (el) {
    //     alert('这里是手势响应事件'+JSON.stringify(el));
    //   });
    // }
  },

  /*#endregion*/

  /*#region 注册绑定数据*/

  computed: {
    imageUrl() {
      return this.fileList.length > 0 ? this.fileList[0].url : this.url;
    }
  },
  components: {
    SignatureCanvas,
    VueSignaturePad,
    DrawingBoard
  },
  data() {
    return {
      right: {
        x: 0,
        y: 0
      },
      image: null,
      url: White,
      signaturePad: {},
      fileList: [],
      signatureCanvasHeight: 0,
      signatureCanvasWidth: 0,
      hammerTest: null
    }
  },
  directives: {
    scroll: {
      inserted: (el, binding) => {
        const cb = binding.value;
        el.addEventListener('mousewheel', function(event) {
          // const direction = e.deltaY > 0 ? 'down' : 'up';
          cb(event)
        })
      }
    },
    contextmenu: {
      inserted: (el, binding, vNode) => {
        if (typeof binding.value !== 'function') {
          // 获取组件名称
          const compName = vNode.context.name;
          // 将警告传递给控制台
          let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be `;
          if (compName) {warn += `Found in component '${compName}' `}
          console.warn(warn);
        }
        const cb = binding.value;

        let press = false;
        const start = (e) => {
          //判断事件是否为click，e.button=0，则为左键，如果是click事件，或者不是按的左键（右键有默认行为），则直接return
          if (e.type === 'click') {
            return;
          }
          if (e.button === 2 || e.buttons === 2) {
            press = true;
            cb(e, "start");
          }
        };
        const cancel = (e) => {
          if (e.type === 'click') {
            return;
          }
          if (e.button === 2 || e.buttons === 2) {
            press = false;
            cb(e, "end");
          }
        };

        // // 运行函数
        // const handler = (e) => {
        //   // 执行传递给指令的方法
        //   binding.value(e)
        // };

        el.addEventListener('contextmenu', function(event) {
          event.returnValue = false;
        });
        // 添加事件监听器
        el.addEventListener("mousedown", start);
        el.addEventListener("mousemove", start);
        el.addEventListener("touchstart", start);
        el.addEventListener("dragstart", start);

        // 取消计时器
        el.addEventListener("mouseout", cancel);
        el.addEventListener("mouseup", cancel);
        el.addEventListener("touchend", cancel);
        el.addEventListener("touchcancel", cancel);
      }
    }
  }

  /*#endregion */

}
</script>
<style scoped lang="scss">
  @import "../../assets/styles/scss/themes/default/views/signature-pic/signature.scss";
</style>
